//
//  UIViewController+lg_keyboardEvent.m
//  ios 架构 demo
//
//  Created by lgb789 on 16/3/21.
//  Copyright © 2016年 com.lgb. All rights reserved.
//

#import "UIViewController+lg_keyboardEvent.h"
#import <objc/runtime.h>

const NSString *KeyboardWillShowKey = @"KeyboardWillShowKey";
const NSString *KeyboardWillHideKey = @"KeyboardHideShowKey";

@implementation UIViewController (lg_keyboardEvent)

-(void)lg_setObject:(id)obj
          forKey:(const NSString *)key
{
    objc_setAssociatedObject(self, (__bridge const void *)(key), obj, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

-(void)lg_addKeyboardWillShowNotificationAction:(KeyboardAction)action
{
    [self lg_setObject:action forKey:KeyboardWillShowKey];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lg_keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}

-(void)lg_addKeyboardWillHideNotificationAction:(KeyboardAction)action
{
    [self lg_setObject:action forKey:KeyboardWillHideKey];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lg_keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)lg_removeKeyboardWillShowNotification
{
    [self lg_setObject:nil forKey:KeyboardWillShowKey];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

-(void)lg_removeKeyboardWillHideNotification
{
    [self lg_setObject:nil forKey:KeyboardWillHideKey];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

-(void)lg_keyboardWillShow:(NSNotification *)notification
{
    NSLog(@"lg will show####!!!!!");
    KeyboardAction action = objc_getAssociatedObject(self, (__bridge const void *)(KeyboardWillShowKey));
    if (action) {
        action(notification);
    }
}

-(void)lg_keyboardWillHide:(NSNotification *)notification
{
    KeyboardAction action = objc_getAssociatedObject(self, (__bridge const void *)(KeyboardWillHideKey));
    if (action) {
        action(notification);
    }
}

@end
